import config from './config';
import regular from './regular.js';
import { getCode } from '@/config/user/api';

export default {
	config,
	//富文本图片处理
	normalRichText(content) {
		let ret = '';
		if (!content) {
			return content;
		}
		ret = content.replace(/<img/g, '<img class="rich-img" ');
		// ret = ret.replace(/<table/g, '<table style="width:100%" ');
		return ret;
	},
	
	
	getUrlParams(url) {
	    // 通过 ? 分割获取后面的参数字符串
	    let urlStr = url.split('?')[1]
	    // 创建空对象存储参数
		let obj = {};
	    // 再通过 & 将每一个参数单独分割出来
		let paramsArr = urlStr.split('&')
		for(let i = 0,len = paramsArr.length;i < len;i++){
	        // 再通过 = 将每一个参数分割为 key:value 的形式
			let arr = paramsArr[i].split('=')
			obj[arr[0]] = arr[1];
		}
		return obj
	},
	decodeURI(url) {
		let decodeURI = decodeURIComponent(url)
		let decodeURIArr = decodeURI.split("")
		decodeURIArr.shift()
		decodeURI = decodeURIArr.join("")
		return decodeURI
	},
	GetQueryString(url, name) {
		const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)")
		const result = url.match(reg)
		if (result != null) {
			return result[2]
		}else{
			return ''
		}
	},
	/*获取验证码*/
	async getCode(that,type) {
		console.log('getCode');
		const common = this;
		let istrue = true;
		const key = uni.getStorageSync('token');
		if (that.verCode.isDownIng) {
			return false;
		}
		let mobile = that?.form?.mobile || that?.userInfo?.member_info?.mobile || '';
		istrue = regular.isTel(mobile);
		if (!istrue) return false;
		let paramData = {
			mobile,
			log_type:type,
			key,
		};
		const res = await getCode(paramData);
		if (res.state == 200) {
			common.downDate(that);
			that.$common.showTip(res.data.msg);
		} else {
			that.$common.showTip(res.data.msg)
		}
	},
	/*验证码倒计时*/
	downDate(that) {
		let i = that.verCode.i;
		that.verCode.t = setInterval(function() {
			that.verCode.text = i + ' S重新获取';
			if (!that.isDownIng) {
				that.verCode.isDownIng = true;
			}
			i--;
			if (i == 0) {
				clearInterval(that.verCode.t);
				that.verCode.isDownIng = false;
				that.verCode.text = '获取验证码';
			}
		}, 1000);
	},
	diaplayTime: function(dateTimeStamp) {
		var result;
		var minute = 60; //把分，时，天，周，半个月，一个月用毫秒表示
		var hour = minute * 60;
		var day = hour * 24;
		var week = day * 7;
		var halfamonth = day * 15;
		var month = day * 30;

		var now = new Date().getTime() / 1000; //获取当前时间毫秒
		var diffValue = now - dateTimeStamp; //时间差
		if (diffValue < 0) {
			return;
		}

		var minC = diffValue / minute; //计算时间差的分，时，天，周，月
		var hourC = diffValue / hour;
		var dayC = diffValue / day;
		var weekC = diffValue / week;
		var monthC = diffValue / month;
		if (monthC >= 1) {
			result = "" + parseInt(monthC) + "月前";
		} else if (weekC >= 1) {
			result = "" + parseInt(weekC) + "周前";
		} else if (dayC >= 1) {
			result = "" + parseInt(dayC) + "天前";
		} else if (hourC >= 1) {
			result = "" + parseInt(hourC) + "小时前";
		} else if (minC >= 1) {
			result = "" + parseInt(minC) + "分钟前";
		} else {
			result = "刚刚";
		}
		return result;
	},

	/*秒转分小时*/
	formatSeconds(value) {
		var secondTime = parseInt(value); // 秒
		var minuteTime = 0; // 分
		var hourTime = 0; // 小时
		if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
			//获取分钟，除以60取整数，得到整数分钟
			minuteTime = parseInt(secondTime / 60);
			//获取秒数，秒数取佘，得到整数秒数
			secondTime = parseInt(secondTime % 60);
			//如果分钟大于60，将分钟转换成小时
			if (minuteTime > 60) {
				//获取小时，获取分钟除以60，得到整数小时
				hourTime = parseInt(minuteTime / 60);
				//获取小时后取佘的分，获取分钟除以60取佘的分
				minuteTime = parseInt(minuteTime % 60);
			}
		}

		// var result = "" + parseInt(secondTime) + "秒";
		var result = '';
		if (parseInt(secondTime) != 0) {
			result = "" + parseInt(secondTime);
		}

		if (minuteTime > 0) {
			result = "" + parseInt(minuteTime) + ":" + result;
		}
		if (hourTime > 0) {
			result = "" + parseInt(hourTime) + ":" + result;
		}
		return result;
	},
	limitFormatTime(date) {
	    var that=this;
	    // 日期格式为 [2019-05-09 20:10:10]
	    date = date.replace(/\-/g,'/');
	    var timestamp = (new Date(date)).valueOf();
	    var nowstr = (new Date()).valueOf();
	    setInterval(function(){
	        nowstr=nowstr-1000
	    },1000)
	    var chazhi = (timestamp - nowstr)/1000;
	    if (chazhi < 0) {
	        chazhi = 0;
	    }
	    var d = Math.floor(chazhi / 3600 / 24);
	    var h = Math.floor((chazhi / 3600) % 24);
	    var m = Math.floor((chazhi % 3600) / 60);
	    var s = Math.floor((chazhi % 3600) % 60);
	    if (h < 10) {
	        h = "0" + h;
	    }
	    if (m < 10) {
	        m = "0" + m;
	    }
	    if (s < 10) {
	        s = "0" + s;
	    }
	     
	    return h + ":" + m + ":" + s
	},       
	/*百度分享*/
	initShare() {
		window._bd_share_config = {
			common: {
				bdSnsKey: {},
				bdText: '',
				bdMini: '2',
				bdMiniList: false,
				bdPic: '',
				bdStyle: '0',
				bdSize: '16'
			},
			slide: {
				type: 'slide',
				bdImg: '0',
				bdPos: 'right',
				bdTop: '101.5'
			},
			// image: { viewList: ['qzone', 'tsina', 'tqq', 'renren', 'weixin'], viewText: '分享到：', viewSize: '16' }
		};
		// 如果有意外 为了避免冲突 先干掉以前的分享script
		const $el = document.querySelector('#baiduShare');
		$el && document.body.removeChild($el);

		const s = document.createElement('script');
		s.type = 'text/javascript';
		s.id = 'baiduShare';
		s.src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + Date.parse(new Date());
		document.body.appendChild(s);
	},

	//时间戳转日期
	timetrans(date, isAll = false) {
		var date = parseInt(date);
		date = date.toString().length == 13 ? new Date(date) : new Date(date * 1000); //如果date为13位不需要乘1000	
		var Y = date.getFullYear() + '-';
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
		if (isAll) {
			var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
			var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
			var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
			return Y + M + D + h + m + s;
		} else {
			return Y + M + D;
		}
	},
	

	timetrans2(date) {
		var date = parseInt(date);
		date = date.toString().length == 13 ? new Date(date) : new Date(date * 1000); //如果date为13位不需要乘1000	
		var Y = date.getFullYear() + '年';
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
		var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日 ';

		var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
		var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
		return Y + M + D + h + m;
	},
	/*
	提示框
	*/
	showTip(title, icon = 'none', duration = 1500) {
		uni.showToast({
			title,
			icon,
			duration,
			mask: true,
		})
	},
	/*
	缓存管理
	moblie,passWord,userInfo
	*/
	storage(key, data) {
		if (data) {
			// #ifdef H5
			uni.setStorageSync(key, data);
			// #endif
			// #ifdef APP-PLUS
			plus.storage.setItem(key, data);
			// #endif
		} else {
			// #ifdef H5
			return uni.getStorageSync(key);
			// #endif
			// #ifdef APP-PLUS
			return plus.storage.getItem(key);
			// #endif
		}
	},
	removeStorage(key) {
		// #ifdef H5
		uni.removeStorageSync(key);
		// #endif
		// #ifdef APP-PLUS
		plus.storage.removeItem(key);
		// #endif
	},
	// #ifdef H5
	h5SetTitle(title) {
		if (document.title == title) {
			return false
		}
		document.title = title || document.title;
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == "micromessenger" && !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/i)) {
			var ifr = document.createElement('iframe')
			ifr.src = "/favicon.ico";
			ifr.onload = function() {
				setTimeout(function() {
					ifr.remove();
				}, 0)
			}
			document.body.appendChild(ifr);
		}
	},
	/*
	判断是否微信环境
	*/
	isWechat() {
		let ua = window.navigator.userAgent.toLowerCase();
		return ua.match(/MicroMessenger/i) == 'micromessenger';
	},
	/*复制文字*/
	copyPolicyNo(id) {
		var clipboard = new Clipboard('#' + id);
		clipboard.on('success', function(e) {
			uni.showToast({
				title: '复制成功',
				icon: 'success',
			})
			e.clearSelection();
		});
	},
	// #endif
	//是否生产模式
	isDev() {
		return process.env.NODE_ENV === 'development';
	},
	/*
	地址联动
	*/
	normalAddres(list) {
		/*不能有多余的属性，要不然app端会卡顿！！！*/
		let arr = [];
		list.forEach(item => {
			let data = {};
			data.label = item.name;
			data.value = item.id;
			data.children = [];
			for (let i = 0, l = item.son.length; i < l; i++) {
				data.children[i] = {
					value: item.son[i].id,
					label: item.son[i].name,
				}
			}
			arr.push(data)
		})
		return arr
	},
	/*地区联动初始值*/
	getAddressInit(data) {
		let pickerValueDefault = [];
		const {
			list,
			province,
			city,
			district,
		} = data;
		console.log("province: " + province);
		console.log("city: " + city);
		console.log("district: " + district);
		for (let pi = 0, pl = list.length; pi < pl; pi++) {
			if (list[pi].value == province) {
				console.log("list[pi].value: " + list[pi].value);
				console.log("pi" + pi);
				pickerValueDefault.push(pi);
				for (let ci = 0, cl = list[pi].children.length; ci < cl; ci++) {
					if (list[pi].children[ci].value == city) {
						console.log("list[pi].children[ci].value" + list[pi].children[ci].value);
						console.log("ci" + ci);
						pickerValueDefault.push(ci);
						if (district && district != 0) {
							for (let ai = 0, al = list[pi].children[ci].children.length; ai < al; ai++) {
								if (list[pi].children[ci].children[ai].value == district) {
									console.log("list[pi].children[ci].children[ai]" + list[pi].children[ci].children[
										ai].value);
									console.log("ai" + ai);
									pickerValueDefault.push(ai);
									break
								}
							}
						} else {
							pickerValueDefault.push(0);
							break
						}
						break
					}
				}
				break
			}
		}
		if (pickerValueDefault.length < 3) {
			for (let i = pickerValueDefault.length, l = 3; i < l; i++) {
				pickerValueDefault.push(0);
			}
		}
		return pickerValueDefault;
	},
	/*回调处理*/
	callback(callback, data = false) {
		if (callback && typeof callback == 'function') {
			callback(data)
		}
	},
	/*返回上一页*/
	goback() {
		let pages = getCurrentPages();
		if (pages.length > 1) {
			uni.navigateBack({
				delta: 1
			});
		} else {
			uni.switchTab({
				url:'/pages/index/index'
			})
		}
	},
	/*获取ip*/
	getIp(callback) {
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = "http://pv.sohu.com/cityjson?ie=utf-8";
		document.getElementsByTagName('head')[0].appendChild(script);
		script.onload = function() {
			if (callback && typeof callback == 'function') {
				callback(returnCitySN)
			}
		} //js加载完成执行方法
	},
	/*获取版本号*/
	getVersion() {
		let version = uni.getSystemInfoSync()['version'];
		version = version.replace(/\./g, "");
		version = version.length > 3 ? version.substring(0, version.length - 1) : version;
		return version
	},

	//过滤emoji表情
	filterEmoji(emoji) {
		let ranges =
			/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig;
		return emoji.replace(ranges, '');
	},
	//获取当前页面对象
	getCurrentPage() {
		let pages = getCurrentPages(); //获取加载的页面
		let currentPage = pages[pages.length - 1]; //获取当前页面的对象
		return currentPage
	},
	//规格
	normalAttr(list, spec_key = false) {
		let res = [];
		let current = null;

		for (let key in list) {
			let obj = {
				key: key,
				list: list[key],
				current: 0,
			}
			res.push(obj)
		}
		//有默认规格
		if (spec_key) {
			current = spec_key.split('_');
			res.forEach((item, index) => {
				let litem = item.list;
				for (let i = 0, l = litem.length; i < l; i++) {
					if (litem[i].item_id == current[index]) {
						item.current = i;
						break
					}
				}
			})
		}
		return res
	},
	//选择规格
	attrChecked(attrlist, speclist) {
		let res = null;
		let attr = [];
		let attrName = [];
		attrlist.forEach(item => {
			let items = item.list[item.current];
			attr.push(items.item_id);
			attrName.push(items.item);
		})
		attr = attr.join('_');
		res = speclist[attr];
		res.attrName = attrName;
		res.attr_name = attrName.join('-');
		parseInt
		return res;
	},
	/*商品过滤*/
	filterGoods(item) {
		return {
			selected: item.selected,
			goods_original_img: item.goods_original_img,
			goods_name: item.goods_name,
			spec_key_name: item.spec_key_name,
			goods_price: item.goods_price,
			store_count: item.store_count,
			goods_num: item.goods_num,
			id: item.id,
			spec_key: item.spec_key,
			spec_key_name: item.spec_key_name,
			goods_id: item.goods_id,
			old_price: item.old_price,
		}
	},
	/*
	地址联动
	*/
	normalAddres(list) {
		/*不能有多余的属性，要不然app端会卡顿！！！*/
		let arr = [];
		list.forEach(item => {
			let data = {};
			data.label = item.name;
			data.value = item.id;
			data.children = [];
			for (let i = 0, l = item.son.length; i < l; i++) {
				data.children[i] = {
					value: item.son[i].id,
					label: item.son[i].name,
					children: []
				}
				item.son[i].son.forEach((items, idx) => {
					data.children[i].children[idx] = {
						value: items.id,
						label: items.name
					};
				});
			}
			arr.push(data)
		})
		// console.log("arr: " + JSON.stringify(arr));
		return arr
	},
	//随机数  
	getRandom(arr, ranNum) {
		// var arr = ['qeqw','asda2s','asda21s','a3sdas','a55sdas','1asdas','as1das','asda3s'];
		// var ranNum = 5;  
		/*
		            let headpicArr = function(){
		    return ['http://img4.imgtn.bdimg.com/it/u=3024387196,1621670548&fm=26&gp=0.jpg', 'http://img4.imgtn.bdimg.com/it/u=4100987808,2324741924&fm=26&gp=0.jpg', 'http://img4.imgtn.bdimg.com/it/u=4120979773,4081271083&fm=26&gp=0.jpg', 'http://img2.imgtn.bdimg.com/it/u=2961748425,612527933&fm=26&gp=0.jpg', 'http://img2.imgtn.bdimg.com/it/u=829044612,3699393036&fm=26&gp=0.jpg', 'http://img5.imgtn.bdimg.com/it/u=324013775,2946570240&fm=26&gp=0.jpg', 'http://img5.imgtn.bdimg.com/it/u=1675225930,3882737045&fm=26&gp=0.jpg', 'http://img5.imgtn.bdimg.com/it/u=2724886373,3500404552&fm=26&gp=0.jpg', 'http://img4.imgtn.bdimg.com/it/u=2166111509,2738448177&fm=26&gp=0.jpg', 'http://img2.imgtn.bdimg.com/it/u=4275757828,1319392454&fm=26&gp=0.jpg', 'http://img2.imgtn.bdimg.com/it/u=2569125699,1916914797&fm=26&gp=0.jpg', 'http://img2.imgtn.bdimg.com/it/u=2717890630,608123158&fm=26&gp=0.jpg']
		}*/
		let result = [];
		for (let i = 0; i < ranNum; i++) {
			let ran = Math.floor(Math.random() * arr.length);
			result.push(arr.splice(ran, 1)[0]);
		};
		return result;
	},

	//乘法 
	accMul(arg1, arg2) {
		var m = 0,
			s1 = arg1.toString(),
			s2 = arg2.toString();
		try {
			m += s1.split(".")[1].length
		} catch (e) {}
		try {
			m += s2.split(".")[1].length
		} catch (e) {}
		return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
	},
	//加法 
	accAdd(arg1, arg2) {
		var r1, r2, m;
		try {
			r1 = arg1.toString().split(".")[1].length
		} catch (e) {
			r1 = 0
		}
		try {
			r2 = arg2.toString().split(".")[1].length
		} catch (e) {
			r2 = 0
		}
		m = Math.pow(10, Math.max(r1, r2))
		return (arg1 * m + arg2 * m) / m
	},
	//减法 
	subtr(arg1, arg2) {
		var r1, r2, m, n;
		try {
			r1 = arg1.toString().split(".")[1].length
		} catch (e) {
			r1 = 0
		}
		try {
			r2 = arg2.toString().split(".")[1].length
		} catch (e) {
			r2 = 0
		}
		m = Math.pow(10, Math.max(r1, r2));
		n = (r1 >= r2) ? r1 : r2;
		return ((arg1 * m - arg2 * m) / m).toFixed(n);
	},
	//会员价
	vipDis(price) {
		return this.accMul(price, config.DISCOUNT)
	},
	//节流
	throttle (func, wait, options) {
	    console.log('throttle方法')
	    var timeout, context, args, result;
	    // 上一次执行回调的时间戳
	    var previous = 0;
	    // 无传入参数时，初始化 options 为空对象
	    if (!options) options = {};
	    var later = function () {
	        // 当设置 { leading: false } 时
	        // 每次触发回调函数后设置 previous 为 0
	        // 不然为当前时间
	        previous = options.leading === false ? 0 : + new Date();
	        // 防止内存泄漏，置为 null 便于后面根据 !timeout 设置新的 timeout
	        timeout = null;
	        // 执行函数
	        result = func.apply(context, args);
	        if (!timeout) context = args = null;
	    };
	    // 每次触发事件回调都执行这个函数
	    // 函数内判断是否执行 func
	    // func 才是我们业务层代码想要执行的函数
	    var throttled = function () {
	        // 记录当前时间
	        var now = + new Date();
	        // 第一次执行时（此时 previous 为 0，之后为上一次时间戳）
	        // 并且设置了 { leading: false }（表示第一次回调不执行）
	        // 此时设置 previous 为当前值，表示刚执行过，本次就不执行了
	        if (!previous && options.leading === false) previous = now;
	        // 距离下次触发 func 还需要等待的时间
	        var remaining = wait - (now - previous);
	        context = this;
	        args = arguments;
	        // 要么是到了间隔时间了，随即触发方法（remaining <= 0）
	        // 要么是没有传入 {leading: false}，且第一次触发回调，即立即触发
	        // 此时 previous 为 0，wait - (now - previous) 也满足 <= 0
	        // 之后便会把 previous 值迅速置为 now
	        // console.log(remaining)
	        // console.log(wait)
	        if (remaining <= 0 || remaining > wait) {
	            // console.log('remaining <= 0 || remaining > wait')
	            if (timeout) {
	                clearTimeout(timeout);
	
	                // clearTimeout(timeout) 并不会把 timeout 设为 null
	                // 手动设置，便于后续判断
	                timeout = null;
	            }
	
	            // 设置 previous 为当前时间
	            previous = now;
	
	            // 执行 func 函数
	            result = func.apply(context, args);
	            if (!timeout) context = args = null;
	        } else if (!timeout && options.trailing !== false) {
	            // console.log('!timeout && options.trailing !== false')
	            // 最后一次需要触发的情况
	            // 如果已经存在一个定时器，则不会进入该 if 分支
	            // 如果 {trailing: false}，即最后一次不需要触发了，也不会进入这个分支
	            // 间隔 remaining milliseconds 后触发 later 方法
	            timeout = setTimeout(later, remaining);
	        }
	        return result;
	    };
	    // 手动取消
	    throttled.cancel = function () {
	        clearTimeout(timeout);
	        previous = 0;
	        timeout = context = args = null;
	    };
	    // 执行 _.throttle 返回 throttled 函数
	    return throttled;
	},
	/*检测新版本*/
    appUpData(isTips = false) {
        console.log('版本检测');
        const common = this;
        let version = plus.runtime.version;
        let apiData = null;
        store.commit('setVersion', version); //版本号
		api.apk({
			version_num: version,
		}).then(res => {
            console.log(res);
			apiData = res.data;
			console.log('apiData'+apiData);
            if ( res.data.status === -1) {
                return uni.showModal({
                    //提醒用户更新
                    title: '更新提示',
                    content: `当前版本是${version},有新版${apiData.data.version}本是否更新？`,
                    showCancel: true,
                    cancelText: '取消',
                    confirmText: '去更新',
                });
            } else {
                if (isTips) {
                    uni.showModal({
                        title: '更新提示',
                        content: `当前是最新版本`,
                        showCancel: false,
                        confirmText: '好的'
                    })
                }
            }
        }).then(datas => {
            const [error, res] = datas;
            if (res.cancel) return false;
            let url = 'http://' + apiData.data.package;
            if (plus.os.name == 'Android') {
                //安卓下载升级
                common.showTip('新版本下载中');
                console.log(url);
                let downloadTask  =  uni.downloadFile({
                    url: encodeURI(url),
                    success: downloadResult => {
						console.log(downloadResult);
						console.log("downloadResult: " + JSON.stringify(downloadResult));
                        if (downloadResult.statusCode === 200) {
                            common.showTip('下载完成')
                            plus.runtime.install(
                                downloadResult.tempFilePath, {
                                    force: false
                                },
                            );
                        }
                    },
                    fail(e) {
                        console.log(e);
                    },
                });
          
            } 
            
            //ios更新
            if(plus.os.name == 'iOS'){
                return false;
                let iosurl = apiData.ios_app || 'https://apps.apple.com/cn/app/%E5%93%94%E5%93%A9%E5%93%94%E5%93%A9-%E5%BC%B9%E5%B9%95%E7%95%AA%E5%89%A7%E7%9B%B4%E6%92%AD%E9%AB%98%E6%B8%85%E8%A7%86%E9%A2%91/id1494852400';
                plus.runtime.openURL(iosurl, function(res) {  
                      console.log(res);  
                });  
            }
                  
        });
    },
    
}
